package com.maolong.spring.core.io;

import cn.hutool.core.lang.Assert;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class UrlResource implements Resource{
    private final URL url;

    public UrlResource(URL url) {
        this.url = url;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        Assert.notNull(url,"URL must not be null");
        InputStream inputStream = url.openConnection().getInputStream();
        return inputStream;
    }

    @Override
    public String getFileName() {
        String uri = this.url.getPath(); // 获取路径部分，排除查询参数等
        int lastSlashIndex = uri.lastIndexOf('/');
        if (lastSlashIndex != -1 && lastSlashIndex < uri.length() - 1) {
            return uri.substring(lastSlashIndex + 1);
        } else {
            return uri;
        }
    }

}
